package cn.tedu._10article.controller;

import cn.tedu._10article.base.response.Result;
import cn.tedu._10article.base.response.StatusCode;
import cn.tedu._10article.mapper.UserMapper;
import cn.tedu._10article.pojo.dto.UserArticleParam;
import cn.tedu._10article.pojo.dto.UserLoginParam;
import cn.tedu._10article.pojo.entity.Article;
import cn.tedu._10article.pojo.vo.ArticleVO;
import cn.tedu._10article.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Tag( name = "文章工程")
@Validated
@RestController
@RequestMapping("/v1/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Operation(summary = "登录功能")
    @ApiOperationSupport(order = 10)
    @PostMapping("/login")
    public Result login(@RequestBody UserLoginParam userLoginParam, HttpSession session) {
        log.debug("userLoginParam: " +  userLoginParam);
        UserVO userVO = userMapper.userLogin(userLoginParam);
        if (userVO != null) {
            session.setAttribute("user", userVO);
            return Result.ok(userVO);
        }
        return Result.fail(StatusCode.USERNAME_PASSWORD_ERROR);
    }

    @Operation(summary = "发表文章功能")
    @ApiOperationSupport(order = 20)
    @PostMapping("/article")
    public Result addArticle(@RequestBody @Validated UserArticleParam userArticleParam, HttpSession session) {
        log.debug("userArticleParam: " +  userArticleParam);
        Article article = new Article();
        BeanUtils.copyProperties(userArticleParam, article);
        article.setUserId(((UserVO) session.getAttribute("user")).getId());
        int i = userMapper.insertArticle(article);
        if (i > 0) {
            return Result.ok();
        }
        return Result.fail();
    }

    @Operation(summary = "查询指定文章功能")
    @ApiOperationSupport(order = 30)
    @PostMapping("/selectByArticleId")
    public Result getArticle(@Range(min = 1, max = 100, message = "文章ID要求在1-100之间") Long id){
        log.debug("id: " + id);
        ArticleVO articleVO = userMapper.selectByArticleId(id);
        return Result.ok(articleVO);
    }


}
